#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtNetwork/qhostaddress.h>
#include <QtNetwork/qhostinfo.h>
#include <QDebug>
#include <QJsonObject>
#include <QMessageBox>
#include <QSqlQuery>
#include <qjsondocument.h>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    this->setWindowTitle("智能饮水机监测系统");
    adduser_dialog = new addUserDialog(this);
    getLoadIP();
    labSocketStat = new QLabel("监听状态:没有打开服务器");
    labSocketStat->setMinimumWidth(150);

    ui->statusbar->addWidget(labSocketStat);
    tcpServer = new QTcpServer(this);

    ui->edit_nowUser->setEnabled(false);
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(onNewsocket()));
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);


    ui->tableWidget_2->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_2->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget_2->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget_2->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    up_ph = 0x3f3f3f3f;
    up_temperature = 0x3f3f3f3f;
    up_waterQuantity = 0x3f3f3f3f;
    up_WaterMargin = 0x3f3f3f3f;
    down_ph = -0x3f3f3f3f;
    down_temperature = -0x3f3f3f3f;
    down_waterQuantity = -0x3f3f3f3f;
    down_WaterMargin = -0x3f3f3f3f;

    ui->lcdNumber_ph->setSegmentStyle(QLCDNumber::Flat);
    edit_debug = ui->plainTextEdit;

    idconnectDev = realdataRead = false;
}


MainWindow::~MainWindow()
{
    //关闭窗口时停止监听
    if (tcpServer->isListening())
        tcpServer->close();;//停止网络监听

    delete ui;
}
void MainWindow::onNewsocket()
{
    //有新连接
    //
    tcpSocket = tcpServer->nextPendingConnection(); //创建socket
    UserList.push_back(qMakePair(tcpSocket, false));
    addLog(QString("收到一个新的连接---") + tcpSocket->peerAddress().toString());

    connect(tcpSocket, SIGNAL(readyRead()),
            this, SLOT(onSocketReadyRead()));
}



void MainWindow::onSocketReadyRead()
{
    //遍历整个用户列表接收用户消息

    //    QStringList   lines;
    for (int i = 0; i < UserList.size(); i++)
    {

        QByteArray readRev = UserList.at(i).first->readAll();
        if(readRev.size() > 0)
        {
            qDebug() << readRev;
            addLog(QString("客户端发来的数据:") + readRev.data());
            QString readStr = readRev.data();
            readStr = readStr.toLower();
            //            DataProcessing(readRev, UserList.at(i).first);
            QString paseData = readStr.mid(readStr.indexOf("cc3f"), readStr.indexOf("3edd") + 4);
            analysis(paseData, UserList.at(i).first);
        }
    }

}
void MainWindow::analysis(QString dat, QTcpSocket *TmptcpSocket)
{
    qDebug() << "read data is " << dat;
     QSqlQuery query;
    QStringList list = dat.split("-");
    qDebug() << "data size is " << list.size();
    if(list.size() < 3)
    {
        addLog(QString("数据长度不对"));
        return ;
    }
    else
    {
        if(list.at(0) == "cc3f" && list.at(list.size() - 1 ) == "3edd")
        {
            addLog(QString("命令---") + list.at(1));
            if(list.at(1) == "login")
            {
                login(list.at(2), list.at(3), TmptcpSocket);
                qDebug() << "login";
            }
            else if(list.at(1) == "regist")
            {
                Regist(list.at(2), list.at(3), TmptcpSocket);
            }
            else if(list.at(1) == "wd")
            {

            }
            else if(list.at(1) == "wcn")
            {

            }
            else if(list.at(1) == "ph")
            {

            }
            else if(list.at(1) == "dts")
            {

            }
            else if(list.at(1) == "afterpassword")
            {

                   bool ans =  query.exec(QString("update User set password = '%1'     where UserName = '%2' ").arg(list.at(3),list.at(2)));
                   if(ans == false)
                   {
                       TmptcpSocket->write("CC3f-ChanState-false-3Edd");
                       qDebug()<<query.lastQuery();
                       addLog("修改失败");
                   }
                   else
                   {
                         qDebug()<<query.lastQuery();
                       TmptcpSocket->write("CC3f-ChanState-true-3Edd");
                        addLog("修改成功");
                   }
            }
            else if(list.at(1) == "readdata")
            {
                QString sendData = (QString("CC3f-01-%1-%2-%3-%4-3Edd\n").arg(QString::number(ui->lcdNumber_ph->value())
                                    , QString::number(ui->lcdNumber_temp->value())
                                    , QString::number(ui->lcdNumber_waQuantity->value())
                                    , QString::number(ui->lcdNumber_waterMargin->value())));
                TmptcpSocket->write(sendData.toUtf8());
            }
            else if(list.at(1) == "01" )
            {
                if(list.at(2) == "full")
                {
                    if(idconnectDev && realdataRead)
                    {

                        tcpClient->write("t1\r\n");
                        ui->pb_dev_control_1->setText("开启");
                        TmptcpSocket->write("CC3f-addWater-01-true-3Edd");

                    }
                    else
                    {
                        addLog("设备未连接");
                        TmptcpSocket->write("CC3f-addWater-01-false-3Edd");

                    }

                }
            }
            else
            {
                addLog(QString("数据解析出错"));
            }
        }
    }

}
void MainWindow::login(QString username, QString password, QTcpSocket *TmptcpSocket)
{

    QSqlQuery query;
    bool ans =   query.exec(QString("select * from User where UserName = %1").arg(username));

    if(ans == true && query.next())
    {
        if(query.value(0).toString() == username
                && query.value(1).toString() == password)
        {
            TmptcpSocket->write("CC3f-Login-true-3Edd\n");
            addLog("登录成功");
            for(int i = 0; i < UserList.size(); i++)
            {
                if(UserList.at(i).first == TmptcpSocket)
                {
                    UserList[i].second = true;
                    break;
                }
            }
            return ;
        }
    }
    else
    {
        addLog("登录失败");
        qDebug() <<  query.lastQuery();
    }
    TmptcpSocket->write("CC3f-Login-false-3Edd\n");
}
void MainWindow::Regist(QString username, QString password, QTcpSocket *TmptcpSocket)
{

    QSqlQuery query;
    bool ans =   query.exec(QString("insert into User values('%1','%2','0')").arg(username, password));

    if(ans == true )
    {

        TmptcpSocket->write("CC3f-Regist -true-3Edd\n");

        return ;
    }
    else
    {

        qDebug() <<  query.lastQuery();
    }
    TmptcpSocket->write("CC3f-Regist -false-3Edd\n");
}

void MainWindow::getLoadIP()
{
    QString hostName = QHostInfo::localHostName(); //本地主机名

    QHostInfo   hostInfo = QHostInfo::fromName(hostName);

    QList<QHostAddress> addList = hostInfo.addresses(); //
    if (!addList.isEmpty())
        for (int i = 0; i < addList.count(); i++)
        {
            QHostAddress aHost = addList.at(i);
            if (QAbstractSocket::IPv4Protocol == aHost.protocol())
            {
                QString IP = aHost.toString();

                //            if (ui->comboIP->findText(IP)<0)
                ui->comboIP->addItem(IP);
            }
        }
}

void MainWindow::DataProcessing(QByteArray Data, QTcpSocket *TmptcpSocket)
{
    QSqlQuery query;
    QJsonParseError parseError;
    QJsonDocument json =  QJsonDocument::fromJson(Data, &parseError);
    if(parseError.error  == QJsonParseError::NoError)
    {
        qDebug() << "收到json数据";
        QJsonObject json_data = json.object();
        QJsonValue type = json_data.value("InfoType");
        if(type.toString() == "realData")
        {
            QJsonValue hpValue = json_data.value("hpValue");
            QJsonValue temperature = json_data.value("temperature");
            QJsonValue waterQuantity = json_data.value("waterQuantity");
            QJsonValue WaterMargin = json_data.value("WaterMargin");


            bool ans = query.exec(QString("insert into RealTimeData(ph,temperature,waterQuantity,WaterMargin,revtime) values(%1,%2,%3,%4,%5)").arg(hpValue.toString(),
                                  temperature.toString(),
                                  waterQuantity.toString(),
                                  WaterMargin.toString(),
                                  QString::number(getLoadTime())));
            if(!ans )
                qDebug() << "DataProcessing " << query.lastQuery();
            ui->lcdNumber_ph->display(hpValue.toString());
            ui->lcdNumber_temp->display(temperature.toString());
            ui->lcdNumber_waQuantity->display(waterQuantity.toString());
            ui->lcdNumber_waterMargin->display(WaterMargin.toString());
            int thpValue = hpValue.toString().toInt();
            int ttemperature = temperature.toString().toInt();
            int twaterQuantity = waterQuantity.toString().toInt();
            int tWaterMargin = WaterMargin.toString().toInt();
            qDebug() << thpValue << " " << ttemperature << " " << twaterQuantity << " " << tWaterMargin;
            if(thpValue > up_ph || thpValue < down_ph)
            {
                QPalette lcdpat =  ui->lcdNumber_ph->palette();
                lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
                ui->lcdNumber_ph->setPalette(lcdpat);
                ui->stackedWidget->setCurrentIndex(0);
                if(thpValue > up_ph)
                    send_warning("up");
                else
                {
                    send_warning("down");
                }
            }
            else
            {
                QPalette lcdpat =  ui->lcdNumber_ph->palette();
                lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::black);
                ui->lcdNumber_ph->setPalette(lcdpat);
            }
            if(ttemperature > up_temperature || ttemperature < down_temperature)
            {
                QPalette lcdpat =  ui->lcdNumber_temp->palette();
                lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
                ui->lcdNumber_temp->setPalette(lcdpat);
                ui->stackedWidget->setCurrentIndex(0);
                if(thpValue > up_temperature)
                    send_warning("up");
                else
                {
                    send_warning("down");
                }
            }
            else
            {
                QPalette lcdpat =  ui->lcdNumber_temp->palette();
                lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::black);
                ui->lcdNumber_temp->setPalette(lcdpat);
            }
            if(twaterQuantity > up_waterQuantity || twaterQuantity < down_waterQuantity)
            {
                QPalette lcdpat =  ui->lcdNumber_waQuantity->palette();
                lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
                ui->lcdNumber_waQuantity->setPalette(lcdpat);
                ui->stackedWidget->setCurrentIndex(0);
                if(thpValue > up_waterQuantity)
                    send_warning("up");
                else
                {
                    send_warning("down");
                }
            }
            else
            {
                QPalette lcdpat =  ui->lcdNumber_waQuantity->palette();
                lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::black);
                ui->lcdNumber_waQuantity->setPalette(lcdpat);
            }
            if(tWaterMargin > up_WaterMargin || tWaterMargin < down_WaterMargin)
            {

                QPalette lcdpat =  ui->lcdNumber_waterMargin->palette();
                lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
                ui->lcdNumber_waterMargin->setPalette(lcdpat);
                ui->stackedWidget->setCurrentIndex(0);
                if(thpValue > up_WaterMargin)
                    send_warning("up");
                else
                {
                    send_warning("down");
                }
            }
            else
            {
                QPalette lcdpat =  ui->lcdNumber_waterMargin->palette();
                lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::black);
                ui->lcdNumber_waterMargin->setPalette(lcdpat);
            }
            for(int i = 0; i < UserList.size(); i++)
            {
                if(UserList.at(i).first != TmptcpSocket && UserList.at(i).second == true)
                    UserList.at(i).first->write(Data);
            }
        }
        else if(type.toString() == "UserLogin")
        {
            QJsonValue name = json_data.value("UserName");
            QJsonValue password = json_data.value("Password");
            UserLogin(name.toString(), password.toString(), TmptcpSocket);
        }

    }
}
void MainWindow::UserLogin(QString username, QString userPassword, QTcpSocket *TmptcpSocket)
{
    QSqlQuery query;
    QJsonDocument document;
    bool ans =   query.exec(QString("select * from User where UserName = %1").arg(username));

    if(ans == true && query.next())
    {

        if(query.value(0).toString() == username
                && query.value(1).toString() == userPassword)
        {
            QVariantHash patientData;
            patientData.insert("type", "UserLogin");
            patientData.insert("status", "success");
            patientData.insert("message", "");


            for(int i = 0; i < UserList.size(); i++)
            {

                if(UserList[i].first == TmptcpSocket)
                {
                    UserList[i].second = true;
                }
            }
            QJsonObject json = QJsonObject::fromVariantHash(patientData);

            document.setObject(json);
            qDebug() << document.toJson().data();

        }
        else//密码错误
        {
            QVariantHash patientData;
            patientData.insert("type", "UserLogin");
            patientData.insert("status", "fail");
            patientData.insert("message", "密码错误");
            QJsonObject json = QJsonObject::fromVariantHash(patientData);

            document.setObject(json);
            qDebug() << document.toJson().data();
        }
    }


    TmptcpSocket->write(document.toJson());

}
void MainWindow::updateuserInfo()
{

    ui->edit_nowUser->setText(nowAccout);
    ui->edit_nowPassword->setText(nowPassword);
    ui->comboBox->setCurrentIndex(userType);
}
void MainWindow::on_pb_addUser_clicked()
{
    QSqlQuery query;
    adduser_dialog->setData("", "", 1);
    adduser_dialog->setTitle("添加用户");
    if(adduser_dialog->exec() == QDialog::Accepted)
    {
        bool ans =   query.exec(QString("insert into User values('%1','%2','%3')").arg(adduser_dialog->getUserName(), adduser_dialog->getPassword(), QString::number(adduser_dialog->getUserType())));
        if(!ans )
        {
            QMessageBox::warning(this, QString("错误")
                                 , QString("添加失败"));
        }
        else
        {
            this->on_pushButton_2_clicked();
        }
    }
}

void MainWindow::on_toolButton_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void MainWindow::on_toolButton_2_clicked()
{
    ui->stackedWidget->setCurrentIndex(1);
}

void MainWindow::on_toolButton_6_clicked()
{
    ui->stackedWidget->setCurrentIndex(2);
}

void MainWindow::on_toolButton_5_clicked()
{
    if(userType == 0)
    {
        QMessageBox::warning(this, QString("错误")
                             , QString("没有访问权限"));
        return ;
    }
    ui->stackedWidget->setCurrentIndex(3);
}

void MainWindow::on_toolButton_4_clicked()
{
    ui->stackedWidget->setCurrentIndex(4);
}

void MainWindow::on_pb_goMain_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_toolButton_7_clicked()
{
    ui->stackedWidget->setCurrentIndex(5);
}
void MainWindow::on_pb_start_servers_clicked()
{
    QString     IP = ui->comboIP->currentText(); //IP地址
    quint16     port = ui->edit_port->value(); //端口
    QHostAddress    addr(IP);
    if(ui->pb_start_servers->text() == "关闭")
    {
        delete  tcpServer;

        //        QMessageBox::warning(this, QString("提示")
        //                             , QString("退出程序才可以关闭服务器"));
        return ;
        ui->pb_start_servers->setText("开启");

    }
    else
    {
        if( tcpServer->listen(addr, port) == true) //
            labSocketStat->setText("监听状态：服务器已开启");
        else
            labSocketStat->setText("监听状态：服务器开启失败");
        ui->pb_start_servers->setText("关闭");


    }


    //    QJsonDocument document;
    //    QVariantHash patientData;
    //    patientData.insert("type","server");
    //    patientData.insert("serverip",IP);
    //    patientData.insert("port",QString::number(tcpServer->serverPort()));
    //    QJsonObject json = QJsonObject::fromVariantHash(patientData);

}

void MainWindow::on_pushButton_2_clicked()
{

    QSqlQuery query;
    query.exec("select *from User");
    ui->tableWidget->setRowCount(0);
    QStringList list;
    list.push_back("用户");
    list.push_back("管理员");
    while(query.next())
    {
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->setRowCount(row + 1);
        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem(list[query.value(2).toInt()]));

    }
}

void MainWindow::on_pb_after_clicked()
{
    QSqlQuery query;
    if(userType == 0)
    {
        QMessageBox::warning(this, QString("错误")
                             , QString("没有修改权限"));
        return ;
    }
    if(ui->edit_nowPassword->text().isEmpty())
    {
        QMessageBox::warning(this, QString("错误")
                             , QString("请输入密码"));
        return ;
    }
    int value = ui->comboBox->currentIndex();
    bool ans =  query.exec(QString("UPDATE User SET password='%1', UserType = '%2'   where UserName='%3' ").arg(ui->edit_nowPassword->text(), QString::number(value), ui->edit_nowUser->text()));
    if(ans == true)
    {
        QMessageBox::information(this, QString("提示")
                                 , QString("修改成功"));

        nowPassword = ui->edit_nowPassword->text();
        userType = ui->comboBox->currentIndex();
    }
}

void MainWindow::on_pushButton_clicked()
{
    QList<QTableWidgetItem *>items = ui->tableWidget->selectedItems();
    QSqlQuery query;
    if(items.size() > 0)
    {
        QString userName =  items.at(0)->text();
        qDebug() << userName;
        query.exec(QString(" DELETE FROM  User where UserName='%3' ").arg(userName));

        this->on_pushButton_2_clicked();

    }
    else
    {
        QMessageBox::information(this, tr("提示"), tr("请选择要删除的项"),
                                 QMessageBox::Yes);
    }
}

void MainWindow::on_pushButton_3_clicked()
{

    QList<QTableWidgetItem *>items = ui->tableWidget->selectedItems();
    QSqlQuery query;
    if(items.size() > 0)
    {
        adduser_dialog->setTitle("修改用户");
        int type = 0;
        if(items.at(2)->text() == "管理员")
            type = 1;
        adduser_dialog->setData( items.at(0)->text(), items.at(1)->text(), type );
        if(adduser_dialog->exec() == QDialog::Accepted)
        {
            bool ans =  query.exec(QString("UPDATE User SET password='%1', UserType = '%2'   where UserName='%3' ").arg(adduser_dialog->getUserName(), adduser_dialog->getPassword(), QString::number(adduser_dialog->getUserType())));
            if(true == ans )
                this->on_pushButton_2_clicked();
        }
    }
    else
    {
        QMessageBox::information(this, tr("提示"), tr("请选择要修改的项"),
                                 QMessageBox::Yes);
    }
}

void MainWindow::on_pb_query_clicked()
{
    QSqlQuery query;
    qDebug() << "data is " << ui->date_start_time->text();
    qDebug() << "data is " << ui->date_end_time->text();

    uint startTime = getFormatTime(ui->date_start_time->text(), "yyyy-MM-dd h:mm");
    uint endTime = getFormatTime(ui->date_end_time->text(), "yyyy-MM-dd h:mm");
    qDebug() << "find time " << startTime << " " << endTime;
    bool ans = query.exec(QString("select *from  RealTimeData where revtime > %1 and revtime <%2;").arg(QString::number(startTime), QString::number(endTime)));
    if(!ans)
    {
        qDebug() << query.lastQuery();
        return ;
    }
    ui->tableWidget_2->setRowCount(0);
    realDatalist.clear();
    int count = 0;
    while(query.next())
    {
        int row = ui->tableWidget_2->rowCount();
        ui->tableWidget_2->setRowCount(row + 1);
        realDatalist.push_back(qMakePair(query.value(0).toUInt(), row));
        qDebug() << query.value(0).toUInt() << " " << row;
        ui->tableWidget_2->setItem(row, 0, new QTableWidgetItem(query.value(1).toString()));
        ui->tableWidget_2->setItem(row, 1, new QTableWidgetItem(query.value(2).toString()));
        ui->tableWidget_2->setItem(row, 2, new QTableWidgetItem(query.value(3).toString()));
        ui->tableWidget_2->setItem(row, 3, new QTableWidgetItem(query.value(4).toString()));
        ++count;
    }
    if(count > 0)
    {
        QMessageBox::information(this, tr("提示"), tr("查询到 %1 条数据").arg(QString::number(count)),
                                 QMessageBox::Yes);
    }
    else
    {
        QMessageBox::information(this, tr("提示"), tr("时间范围内没有查询到数据"),
                                 QMessageBox::Yes);
    }
}
uint MainWindow::getLoadTime()
{
    QDateTime time = QDateTime::currentDateTime();   //获取当前时间
    return time.toTime_t();   //将当前时间转为时间戳
}
uint MainWindow::getFormatTime(QString data, QString format)
{
    QDateTime time;
    time = QDateTime::fromString(data, format);
    //      time.
    return time.toTime_t();
}

void MainWindow::on_pushButton_4_clicked()
{
    qApp->exit(0);
}


void MainWindow::on_pushButton_7_clicked()
{
    if(!ui->lineEdit_up_1->text().isEmpty())
        up_ph =  ui->lineEdit_up_1->text().toInt();
    if(!ui->lineEdit_up_2->text().isEmpty())
        up_temperature =  ui->lineEdit_up_1->text().toInt();
    if(!ui->lineEdit_up_3->text().isEmpty())
        up_waterQuantity =  ui->lineEdit_up_1->text().toInt();
    if(!ui->lineEdit_up_4->text().isEmpty())
        up_WaterMargin =  ui->lineEdit_up_1->text().toInt();
}

void MainWindow::on_pushButton_8_clicked()
{
    if(!ui->lineEdit_down_1->text().isEmpty())
        down_ph =  ui->lineEdit_down_1->text().toInt();
    if(!ui->lineEdit_down_2->text().isEmpty())
        down_temperature =  ui->lineEdit_down_1->text().toInt();
    if(!ui->lineEdit_down_3->text().isEmpty())
        down_waterQuantity =  ui->lineEdit_down_1->text().toInt();
    if(!ui->lineEdit_down_4->text().isEmpty())
        down_WaterMargin =  ui->lineEdit_down_1->text().toInt();
}

void MainWindow::on_pushButton_5_clicked()
{
    QList<QTableWidgetItem *>items = ui->tableWidget_2->selectedItems();
    if(items.size() > 0)
    {
        int delrow = ui->tableWidget_2->row(items.at(0));
        qDebug() << "row" << delrow << "  " << realDatalist[delrow].first;
        QSqlQuery query;
        query.exec(QString("delete from RealTimeData where id = %1").arg(QString::number(realDatalist[delrow].first)));
        this->on_pb_query_clicked();

    }
    else
    {
        QMessageBox::information(this, tr("提示"), tr("请选择一个项"),
                                 QMessageBox::Yes);
    }
}

void MainWindow::on_pushButton_6_clicked()
{
    QSqlQuery query;
    uint startTime = getFormatTime(ui->date_start_time->text(), "yyyy-MM-dd h:mm");
    uint endTime = getFormatTime(ui->date_end_time->text(), "yyyy-MM-dd h:mm");
    bool ans = query.exec(QString("delete from  RealTimeData where revtime > %1 and revtime <%2;").arg(QString::number(startTime), QString::number(endTime)));
    if(ans == false)
    {
        QMessageBox::warning(this, tr("提示"), tr("删除失败"),
                             QMessageBox::Yes);
    }
    this->on_pb_query_clicked();
}
void MainWindow::connectTCP(QString ip, int port)
{

    tcpClient = new QTcpSocket(this);
    tcpClient->connectToHost(ip, port);
    if (tcpClient->waitForConnected(1000))
    {


        connect(tcpClient, &QTcpSocket::readyRead, this, [ = ]()
        {
            QSqlQuery query;
            QByteArray  read =  tcpClient->readAll();
            QString  StrRead = read.data();
            StrRead =  StrRead.toLower();
            addLog(QString("底层发来的数据：") + StrRead + QString("---end"));
            QString paseData = StrRead.mid(StrRead.indexOf("cc3f"), StrRead.indexOf("3edd") + 4);
            addLog(paseData);
            QStringList list = paseData.split("-");
            if(list.size() < 7)
            {
                addLog("数据解析错误");

            }
            else
            {
                realdataRead = true;
                for(int i = 0; i < list.size(); i++)
                {
                    addLog(list.at(i));
                }
                ui->lcdNumber_ph->display(list.at(2));
                ui->lcdNumber_temp->display(list.at(3));
                ui->lcdNumber_waQuantity->display(list.at(4));
                ui->lcdNumber_waterMargin->display(list.at(5));
                bool ans = query.exec(QString("insert into RealTimeData(ph,temperature,waterQuantity,WaterMargin,revtime) values(%1,%2,%3,%4,%5)").arg(list.at(2),
                                      list.at(3),
                                      list.at(4),
                                      list.at(5),
                                      QString::number(getLoadTime())));
                if(!ans )
                    addLog(QString( "DataProcessing ") + query.lastQuery());
                QString sendData = (QString("CC3f-01-%1-%2-%3-%4-3Edd\n").arg(QString::number(ui->lcdNumber_ph->value())
                                    , QString::number(ui->lcdNumber_temp->value())
                                    , QString::number(ui->lcdNumber_waQuantity->value())
                                    , QString::number(ui->lcdNumber_waterMargin->value())));
                for(int i = 0; i < UserList.size(); i++)
                {

                    UserList.at(i).first->write(sendData.toUtf8());
                }

                int thpValue =  ui->lcdNumber_ph->value();
                int ttemperature = ui->lcdNumber_temp->value();
                int twaterQuantity =ui->lcdNumber_waQuantity->value();
                int tWaterMargin =ui->lcdNumber_waterMargin->value();
                qDebug() << thpValue << " " << ttemperature << " " << twaterQuantity << " " << tWaterMargin;
               qDebug()<<"up_ph "<<up_ph<<" "<<down_ph;
                if(thpValue > up_ph || thpValue < down_ph)
                {
                    QPalette lcdpat =  ui->lcdNumber_ph->palette();
                    lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
                    ui->lcdNumber_ph->setPalette(lcdpat);
                    ui->stackedWidget->setCurrentIndex(0);
                    if(thpValue > up_ph)
                        send_warning("up");
                    else
                    {
                        send_warning("down");
                    }
                }
                else
                {
                    QPalette lcdpat =  ui->lcdNumber_ph->palette();
                    lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::black);
                    ui->lcdNumber_ph->setPalette(lcdpat);
                }
                qDebug()<<"ttemperature "<<up_temperature<<" "<<down_temperature;
                if(ttemperature > up_temperature || ttemperature < down_temperature)
                {
                    QPalette lcdpat =  ui->lcdNumber_temp->palette();
                    lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
                    ui->lcdNumber_temp->setPalette(lcdpat);
                    ui->stackedWidget->setCurrentIndex(0);
                    if(ttemperature > up_temperature)
                        send_warning("up");
                    else
                    {
                        send_warning("down");
                    }
                }
                else
                {
                    QPalette lcdpat =  ui->lcdNumber_temp->palette();
                    lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::black);
                    ui->lcdNumber_temp->setPalette(lcdpat);
                }
                qDebug()<<"twaterQuantity "<<up_waterQuantity<<" "<<down_waterQuantity;

                if(twaterQuantity > up_waterQuantity || twaterQuantity < down_waterQuantity)
                {
                    QPalette lcdpat =  ui->lcdNumber_waQuantity->palette();
                    lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
                    ui->lcdNumber_waQuantity->setPalette(lcdpat);
                    ui->stackedWidget->setCurrentIndex(0);
                    if(twaterQuantity > up_waterQuantity)
                        send_warning("up");
                    else
                    {
                        send_warning("down");
                    }
                }
                else
                {
                    QPalette lcdpat =  ui->lcdNumber_waQuantity->palette();
                    lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::black);
                    ui->lcdNumber_waQuantity->setPalette(lcdpat);
                }
                qDebug()<<"tWaterMargin "<<up_WaterMargin<<" "<<down_WaterMargin;

                if(tWaterMargin > up_WaterMargin || tWaterMargin < down_WaterMargin)
                {

                    QPalette lcdpat =  ui->lcdNumber_waterMargin->palette();
                    lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
                    ui->lcdNumber_waterMargin->setPalette(lcdpat);
                    ui->stackedWidget->setCurrentIndex(0);
                    if(tWaterMargin > up_WaterMargin)
                        send_warning("up");
                    else
                    {
                        send_warning("down");
                    }
                }
                else
                {
                    QPalette lcdpat =  ui->lcdNumber_waterMargin->palette();
                    lcdpat.setColor(QPalette::Normal, QPalette::WindowText, Qt::black);
                    ui->lcdNumber_waterMargin->setPalette(lcdpat);
                }
            }


        });
        QMessageBox::information(NULL, tr("提示"), tr("连接设备成功"),
                                 QMessageBox::Yes);
        idconnectDev = true;
    }
    else
    {
        QMessageBox::warning(NULL, tr("错误"), tr("连接设备失败"),
                             QMessageBox::Yes);
    }
}


void MainWindow::send_warning(QString info)
{
    QString sendData = QString("CC3f-Warn-01-%1-3Edd\n").arg(info);
    addLog(sendData);
    for(int i = 0; i < UserList.size(); i++)
    {

        UserList.at(i).first->write(sendData.toUtf8());
    }

}

void MainWindow::on_pb_conec_dev_clicked()
{
    if(ui->edit_dev_ip->text().isEmpty())
    {
        QMessageBox::warning(NULL, tr("错误"), tr("请输入完整的信息"),
                             QMessageBox::Yes);
        return ;
    }
    this->connectTCP(ui->edit_dev_ip->text(), ui->edit_port_2->value());
}

void MainWindow::on_pb_dev_control_1_clicked()
{
    if(idconnectDev && realdataRead)
    {

        if(ui->pb_dev_control_1->text() == "关闭")
        {
            tcpClient->write("t1\r\n");
            ui->pb_dev_control_1->setText("开启");
        }
        else
        {
            tcpClient->write("t2\r\n");

            ui->pb_dev_control_1->setText("关闭");
        }
    }
}

void MainWindow::on_pb_dev_control_2_clicked()
{
    if(idconnectDev && realdataRead)
    {

        if(ui->pb_dev_control_2->text() == "关闭")
        {
            tcpClient->write("t3\r\n");
            ui->pb_dev_control_2->setText("开启");
        }
        else
        {
            tcpClient->write("t4\r\n");

            ui->pb_dev_control_2->setText("关闭");
        }
    }
}
